#! /usr/local/bin/python

# Web 2.0 API

import cgitb; cgitb.enable()
import cgi
import urllib
import urllib2
from xml.dom import minidom
from xml.dom.minidom import Document
from time import gmtime, strftime

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

file = urllib2.urlopen('http://personal.cs.cityu.edu.hk/~51158405/blog/api/comment.xml')
data = file.read()
file.close()

xmldoc = minidom.parseString(data)

# get form variables (if desired)
form = cgi.FieldStorage()
if 'id' in form:
    pid = form['id'].value
else:
    pid = ''
if 'name' in form:
    name = form['name'].value
else:
    name = 'Anonymous'
if 'content' in form:
    content = form['content'].value
else:
    content = ''

# create xml node for the new comment
doc = Document()
newComment = doc.createElement('comment')

user_n = doc.createElement('user')
user_t = doc.createTextNode(name)
user_n.appendChild(user_t)

time_n = doc.createElement('time')
print strftime('%Y-%m-%d %H:%M:%S', gmtime())
time_t = doc.createTextNode(strftime('%Y-%m-%d %H:%M:%S', gmtime()))
time_n.appendChild(time_t)

content_n = doc.createElement('content')
content_t = doc.createTextNode(content)
content_n.appendChild(content_t)

newComment.appendChild(user_n)
newComment.appendChild(time_n)
newComment.appendChild(content_n)

try:
    posts = xmldoc.getElementsByTagName("post")
    exist = false
    for post in posts:
        _id = getText(post.getElementsByTagName("id")[0].childNodes)
        if pid == _id:
            # add comment to a existing post
            post.appendChild(newComment)
            exist = true
            
    if exist == false:
        # add a new post node
        newPostNode = doc.createElement('post')
        id_n = doc.createElement('id')
        id_t = doc.createTextNode(pid)
        newPostNode.appendChild(id_n)
        newPostNode.appendChild(newComment)
        xmldoc.appendChild(newPostNode)
except:
    print "Error!"
  
# write xmldoc to an xml file
file = urllib2.urlopen('http://personal.cs.cityu.edu.hk/~51158405/blog/api/comment.xml')
data = file.write(xmldoc)
file.close()

# print out the content header
print 'Content-type: text/html\n\n'
print 'Comment added!'
